package com.chen.palmar.project.home;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.dialog.SelectPickerDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.ApplyInfoEntity;
import com.chen.palmar.entity.ApplyInfoRequest;
import com.chen.palmar.entity.ApplyManagerEntity;
import com.chen.palmar.entity.ApplyTagEntity;
import com.chen.palmar.entity.DetailEntity;
import com.chen.palmar.project.agency.CityPickerActivity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.primb.androidlibs.utils.FileUtils;
import com.zaaach.citypicker.model.City;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.valuesfeng.picker.ImageSelectActivity;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import rx.Observable;
import rx.Subscription;

/**
 * Created by chen on 2018/1/3.
 * 发布信息（供应，采购）
 */

public class ApplyInfoActivity extends BaseActivity {
    public static final int EVENT_INFO_CODE = 1;
    public static final int REQUEST_CODE_ADDRESS = 2;
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.et_apply_title)
    EditText etApplyTitle;
    @Bind(R.id.et_apply_desc)
    EditText etApplyDesc;
    @Bind(R.id.tv_apply_tag)
    TextView tvApplyTag;
    @Bind(R.id.et_apply_phone)
    EditText etApplyPhone;
    @Bind(R.id.tv_apply_address)
    TextView tvApplyAddress;
    @Bind(R.id.cb_apply_top)
    CheckBox cbApplyTop;
    @Bind(R.id.tv_apply_top_time)
    TextView tvApplyTopTime;
    @Bind(R.id.tv_apply_price)
    TextView tvApplyPrice;
    @Bind(R.id.rv_apply_img)
    RecyclerView rvApplyImg;
    @Bind(R.id.btn_apply_info)
    Button btnApplyInfo;
    private ApplyInfoRequest request;
    private List<String> imgList = new ArrayList<>();
    private static final int REQUEST_CODE_IMG = 1;
    BaseQuickAdapter<String, BaseViewHolder> adapterImg;
    private ApplyManagerEntity.DataBean entity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        titleBar.setText("发布");
        toolBar.setNavigationOnClickListener(v -> ApplyInfoActivity.this.finish());

        request = new ApplyInfoRequest();

        request.setType(getIntent().getStringExtra("type"));

        if (request.getType().equals("1")) {
            etApplyDesc.setHint("请输入采购信息介绍");
        } else {
            etApplyDesc.setHint("请输入供应信息介绍");
        }

        imgList.add(null);

        entity = ((ApplyManagerEntity.DataBean) getIntent().getSerializableExtra("entity"));

        if (entity != null) {
            getDataForWeb(entity.getArticleId() + "");
        }

        rvApplyImg.setNestedScrollingEnabled(false);
        GridLayoutManager layoutManager = new GridLayoutManager(ApplyInfoActivity.this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvApplyImg.setLayoutManager(layoutManager);
        adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_img) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                SquareImageView view = (SquareImageView) helper.getView(R.id.iv_item_img);
                if (null == item) {
                    Glide.with(ApplyInfoActivity.this).load(R.mipmap.apply_add_img).override(AppConstant.SCREEN_WIDTH / 4, AppConstant.SCREEN_WIDTH / 4).placeholder(R.mipmap.apply_add_img).error(R.mipmap.apply_add_img).into(view);
                } else {
                    Glide.with(ApplyInfoActivity.this).load(item).override(AppConstant.SCREEN_WIDTH / 4, AppConstant.SCREEN_WIDTH / 4).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).into(view);
                }
            }
        };
        adapterImg.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == imgList.size() - 1) {
                    getImgInfo();
                }
            }
        });
        adapterImg.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                if (position != imgList.size() - 1) {
                    imgList.remove(position);
                    if (null != imgList.get(imgList.size() - 1)) {
                        imgList.add(null);
                        adapter.notifyDataSetChanged();
                    } else {
                        adapterImg.notifyItemRemoved(position);
                    }
                }
                return false;
            }
        });
        rvApplyImg.setItemAnimator(new DefaultItemAnimator());
        adapterImg.setNewData(imgList);
        rvApplyImg.setAdapter(adapterImg);
    }

    private void getDataForWeb(String articleId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("articleId", articleId);
        Subscription subscribe = DataCenter.detailInfo(map).subscribe(new HttpSubscriber<DetailEntity>(this, showLoading("加载中")) {
            @Override
            public void onNext(DetailEntity detailEntity) {
                try {
                    setDataToView(detailEntity);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                }
            }
        });
        subscription.add(subscribe);
    }

    private void setDataToView(DetailEntity detailEntity) {
        DetailEntity.DataBean data = detailEntity.getData();
        etApplyTitle.setText(data.getTitle());
        etApplyDesc.setText(data.getContent());
        etApplyPhone.setText(data.getMobile());
        request.setType(data.getType() + "");
        request.setAddres_id(data.getAddress_id() + "");
        tvApplyAddress.setText(data.getAddress_detail());
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_apply_info;
    }

    @OnClick({R.id.tv_apply_tag, R.id.cb_apply_top, R.id.tv_apply_top_time, R.id.tv_apply_address, R.id.btn_apply_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_apply_tag:
                showTagDialog();
                break;
            case R.id.cb_apply_top:
                break;
            case R.id.tv_apply_top_time:
                break;
            case R.id.tv_apply_address:
                startActivityForResult(new Intent(this, CityPickerActivity.class), REQUEST_CODE_ADDRESS);
                break;
            case R.id.btn_apply_info:
                applyInfo();
                break;
        }
    }

    private void getImgInfo() {
        Picker.from(this).count(9 - imgList.size() + 1).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMG && resultCode == Activity.RESULT_OK) {
            List<Uri> imgList = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
            for (int i = 0; i < imgList.size(); i++) {
                this.imgList.add(0, FileUtils.getRealPathFromUri(this, imgList.get(i)));
            }
            if (this.imgList.size() >= 10) {
                this.imgList.remove(this.imgList.size() - 1);
            }
            adapterImg.setNewData(this.imgList);
        } else if (requestCode == REQUEST_CODE_ADDRESS && resultCode == RESULT_OK) {
            if (data != null) {
                City city = (City) data.getSerializableExtra(CityPickerActivity.KEY_PICKED_CITY);
                tvApplyAddress.setText(city.getName());
                request.setAddres_id(city.getAddessId() + "");
                request.setAddress_name(city.getName());
            }
        }
    }

    private void showTagDialog() {
        SelectPickerDialog<ApplyTagEntity.DataBean> dialog = new SelectPickerDialog<>();
        dialog.setListener(new SelectPickerDialog.OnPickedListener<ApplyTagEntity.DataBean>() {
            @Override
            public void onPickCompleted(ApplyTagEntity.DataBean dataDesc) {
                request.setLabel_id(dataDesc.getLabelId() + "");
                tvApplyTag.setText(dataDesc.getLabelName());
            }
        });
        dialog.show(getSupportFragmentManager());
        getTagList(dialog);
    }

    private void getTagList(SelectPickerDialog dialog) {
        Subscription subscribe = DataCenter.applyTagListInfo().subscribe(new HttpSubscriber<ApplyTagEntity>(this, null) {
            @Override
            public void onNext(ApplyTagEntity tagListEntity) {
                if (null != dialog && dialog.isVisible()) {
                    dialog.setDateList(tagListEntity.getData());
                }
            }
        });
        subscription.add(subscribe);
    }

    private void applyInfo() {
        request.setTitle(etApplyTitle.getText().toString());
        request.setContent(etApplyDesc.getText().toString());
        request.setMobile(etApplyPhone.getText().toString());
        request.setImgList(imgList);
        if (!checkParams()) {
            return;
        }
        Observable<ApplyInfoEntity> applyInfo;
        if (entity == null) {
            applyInfo = DataCenter.applyInfo(request);
        } else {
            applyInfo = DataCenter.updateApplyInfo(request);
        }
        Subscription subscribe = applyInfo.subscribe(new HttpSubscriber<ApplyInfoEntity>(this, showLoading("发布中")) {
            @Override
            public void onNext(ApplyInfoEntity applyInfoEntity) {
                showToast(applyInfoEntity.getMessage());
                ApplyInfoActivity.this.finish();
                EventBus.getDefault().post(new MessageEvent(EVENT_INFO_CODE));
            }
        });
        subscription.add(subscribe);
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(request.getType())) {
            return false;
        } else if (TextUtils.isEmpty(request.getAddress_name())) {
            showToast("请选择城市");
            return false;
        } else if (TextUtils.isEmpty(request.getContent())) {
            showToast("请输入描述信息");
            return false;
        } else if (TextUtils.isEmpty(request.getLabel_id())) {
            showToast("请选择标签");
            return false;
        } else if (TextUtils.isEmpty(request.getMobile())) {
            showToast("请输入手机号");
            return false;
        } else if (TextUtils.isEmpty(request.getTitle())) {
            showToast("请输入标题");
            return false;
        } else {
            return true;
        }
    }
}
